package com.lzh.hosp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzh.hosp.model.Doctor;
import com.lzh.hosp.model.ResponseResult;
import com.lzh.hosp.model.dto.DoctorQueryDto;
import com.lzh.hosp.model.dto.DoctorUpdateAuthDto;
import com.lzh.hosp.model.vo.DoctorQueryVo;
import com.lzh.hosp.service.DoctorService;
import com.lzh.hosp.utils.RedisCache;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/doctor")
@Tag(name="医生管理")
public class DoctorController {
    @Autowired
    HttpServletRequest req;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/list")
    public ResponseResult list(DoctorQueryDto doctorQueryDto){
        Long depcode = doctorQueryDto.getDepcode();
        String username = doctorQueryDto.getUsername();
        Integer authStatus = doctorQueryDto.getAuthStatus();

        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(authStatus),"auth_status",authStatus);
        wrapper.eq(!StringUtils.isEmpty(depcode),"depcode",depcode);
        wrapper.eq(!StringUtils.isEmpty(username),"username",username);
        Page<Doctor> list = doctorService.page(getPage(),wrapper);

        return ResponseResult.ok(list);
    }


    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('sys:certificate:save')")
    public ResponseResult save(@RequestBody @Validated Doctor doctor){
        //查询是否已经存在医生信息
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",doctor.getAccountId());
        Doctor doc = doctorService.getOne(wrapper);
        if (StringUtils.isEmpty(doc)){//为空，添加医生信息
            doctor.setAuthStatus(0);
            doctorService.save(doctor);
            return ResponseResult.ok();
        }else{
            return ResponseResult.fail("添加失败");
        }
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyAuthority('sys:certificate:update')")
    public ResponseResult update(@RequestBody @Validated Doctor doctor){
        doctor.setAuthStatus(0);
        boolean flag = doctorService.updateById(doctor);
        //清除redis缓存信息
        redisCache.deleteObject("certificate:advice:"+doctor.getId());
        return flag?ResponseResult.ok():ResponseResult.ok("更新失败");
    }

    //根据用户id获取医生信息
    @GetMapping("/findByUserId/{userId}")
    public ResponseResult findByUserId(@PathVariable Long userId){
        DoctorQueryVo doctorQueryVo = doctorService.getDocInfo(userId);
        return ResponseResult.ok(doctorQueryVo);
    }

    //根据id获取医生信息
    @GetMapping("findById/{id}")
    public ResponseResult findById(@PathVariable Long id){
        Doctor doctor = doctorService.getById(id);
        return ResponseResult.ok(doctor);
    }

    //根据科室id查询出所有的医生列表
    @GetMapping("/findByDepcode/{depcode}")
    public ResponseResult find(@PathVariable Long depcode){
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("depcode",depcode);
        List<Doctor> list = doctorService.list(wrapper);
        return ResponseResult.ok(list);
    }

    //判断医生是否已认证
    @GetMapping("/isAuth")
    public ResponseResult isAuth(HttpServletRequest request){
        boolean auth = doctorService.isAuth(request);
        return auth?ResponseResult.ok(true):ResponseResult.ok(false);
    }

    //更新认证状态
    @PostMapping("/updateAuthStatus")
    @PreAuthorize("hasAnyAuthority('sys:certificate:check')")
    public ResponseResult updateAuthStatus(@RequestBody DoctorUpdateAuthDto doctorUpdateAuthDto){
        Doctor doctor = doctorService.getById(doctorUpdateAuthDto.getId());
        doctor.setAuthStatus(doctorUpdateAuthDto.getAuthStatus());
        Integer authStatus = doctor.getAuthStatus();
        if (authStatus==2){//说明不通过
            //在redis存入建议
            redisCache.setCacheObject("certificate:advice:"+doctor.getId(),doctorUpdateAuthDto.getAdvice());
        }
        boolean flag = doctorService.updateById(doctor);

        return flag?ResponseResult.ok():ResponseResult.fail("更新失败");
    }

    //获取修改意见
    @GetMapping("/getAdvice/{id}")
    public ResponseResult getAdvice(@PathVariable Long id){
        String advice = (String)redisCache.getCacheObject("certificate:advice:" + id);
        return ResponseResult.ok(advice);
    }

    /**
     * 获取页面
     * @return
     */
    public Page getPage() {
        int current = ServletRequestUtils.getIntParameter(req, "current", 1);
        int size = ServletRequestUtils.getIntParameter(req, "size", 10);

        return new Page(current, size);
    }

}
